<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="classNames">
        <el-input v-model="queryParams.classNames" placeholder="请选择班级" @focus="selectClass()">
        </el-input>
        <el-input v-model="queryParams.classIds" v-if="false" placeholder="请选择班级" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
         <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:schedule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edu:schedule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['edu:schedule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:schedule:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课表名称" align="center" prop="scheduleName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="科目" align="center" prop="subjectName" />
      <el-table-column label="教学计划" align="center" prop="teachPlanName" />
      <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:schedule:edit']"
          >修改</el-button>
          -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:schedule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排课基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="班级科目ID" prop="classSubId">
          <el-input v-model="form.classSubId" placeholder="请输入班级科目ID" />
        </el-form-item>
        <el-form-item label="教学计划ID" prop="teachPlanId">
          <el-input v-model="form.teachPlanId" placeholder="请输入教学计划ID" />
        </el-form-item>
        <el-form-item label="班级科目排课名称" prop="scheduleName">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.scheduleName"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择班级科目排课名称">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio-group v-model="form.status">
                    <el-radio
                              v-for="dict in statusOptions"
                              :key="dict.dictValue"
                              :label="dict.dictValue"
                            >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="班级选择框" :visible.sync="openClassSelect" width="1000px" append-to-body>
      <el-form :model="queryParamsClass" ref="queryFormClass" :inline="true" v-show="showSearch" label-width="120px">
        <el-form-item label="归属校区" prop="campusId">
          <treeselect style="width:200px" v-model="queryParamsClass.campusId" :options="campusOptions" 
                  :multiple="false" :disableBranchNodes="true"
                  :show-count="true" placeholder="请选择归属校区" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input
            v-model="queryParamsClass.className"
            placeholder="请输入班级名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="行课学期" prop="classTerm">
          <el-select v-model="queryParamsClass.classTerm" placeholder="请选择行课学期" clearable size="small">
            <el-option
                    v-for="dict in classTermOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="行课时间" prop="classBeginDate">
          <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
        </el-form-item>
        -->
        <el-form-item label="班主任" prop="masterUserId">
          <el-select
                v-model="queryParamsClass.masterUserId"
                placeholder="请输入班主任"
                clearable
                size="small"
                style="width: 200px"
              >
                <el-option
                  v-for="user in masterUserOptions"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId"
                />
              </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQueryClass">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryClass">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" ref="tableClassSelect" :data="classInfoList" @selection-change="handleSelectionChangeClass">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="归属校区" align="center" prop="campusName" width="180" />
        <el-table-column label="班级名称" align="center" prop="className" width="180" />
        <el-table-column label="开课科数" align="center" prop="subjectNum" width="100" />
        <el-table-column label="开课总天数" align="center" prop="subjectDays" width="100" />
        <el-table-column label="行课学期" :formatter="classTermFormat" align="center" prop="classTerm" width="100" />
        <el-table-column label="行课开始时间" align="center" prop="classBeginDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.classBeginDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行课结束时间" align="center" prop="classEndDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.classEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="班主任" align="center" prop="masterUserName" width="100" />
      </el-table> 
      <pagination
        v-show="totalClass>0"
        :total="totalClass"
        :page.sync="queryParamsClass.pageNum"
        :limit.sync="queryParamsClass.pageSize"
        @pagination="getListClass"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleClassSelect">确定</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetClassCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule, exportSchedule } from "@/api/edu/schedule";
import { listClassInfo  } from "@/api/edu/classInfo";
import { listAllUserByDeptId } from "@/api/system/user";
import { treeselectByType } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Schedule",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排课基础信息表格数据
      scheduleList: [],
      statusOptions: [],
      classInfoList: [],
      campusOptions: [],
      classTermOptions: [],
      masterUserOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classIds: null,
        classNames: null,
        classSubId: null,
        teachPlanId: null,
        scheduleName: null,
        status: null,
      },
      // 表单参数
      form: {},
      rules: [],
      dateRange: [],
      // 班级查询内容
      queryParamsClass: {
        pageNum: 1,
        pageSize: 6,
        campusId: null,
        classCode: null,
        className: null,
        subjectType: null,
        classType: null,
        subjectNum: null,
        subjectDays: null,
        grade: null,
        classTerm: null,
        classBeginDate: null,
        classEndDate: null,
        masterUserId: null,
        status: '0',
      },
      openClassSelect: false,
      totalClass: 0,
      loadingText: '加载班级',
    };
  },
  watch: {
    'queryParamsClass.campusId': 'selectQueryForm',
  },
  created() {
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getList();
  },
  methods: {
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    
    /** 查询排课基础信息列表 */
    getList() {
      this.loading = true;
      listSchedule(this.queryParams).then(response => {
        this.scheduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scheduleId: null,
        classSubId: null,
        teachPlanId: null,
        scheduleName: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scheduleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加排课基础信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const scheduleId = row.scheduleId || this.ids
      getSchedule(scheduleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改排课基础信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scheduleId != null) {
            updateSchedule(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchedule(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scheduleIds = row.scheduleId || this.ids;
      this.$confirm('是否确认删除排课基础信息编号为"' + scheduleIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSchedule(scheduleIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有排课基础信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSchedule(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 查询班级信息列表 */
    selectClass() {
      // 选择班级弹出框
      this.openClassSelect = true
      let that = this
      setTimeout(function () {
        that.queryCampus();
        that.getDicts("edu_class_term").then(response => {
          that.classTermOptions = response.data;
        });
        that.handleQueryClass() // 执行列表查询
      }, 500);
    },
    classTermFormat(row, column) {
      return this.selectDictLabel(this.classTermOptions, row.classTerm)
    },
    getListClass() {
      this.loading = true;
      listClassInfo(this.addDateRange(this.queryParamsClass, this.dateRange)).then(response => {
        this.classInfoList = response.rows;
        this.totalClass = response.total;
        this.loading = false;
        this.initClassHandler() // 初始化查询条件
      });
    },
    initClassHandler() {
      //this.$nextTick(() => {
        let that = this
        that.classInfoList.forEach((item, index) => {
          if(that.queryParams.classIds) {
            let v_classIds = that.queryParams.classIds + ','
            v_classIds.split(',').forEach(ele => {
              if(ele.toString() === item.classId.toString()) {
                // 判断在返回列表中存在，就设置选中
                this.$nextTick( ()=> {
                  this.$refs.tableClassSelect.toggleRowSelection(this.classInfoList[index], true)
                })
              }
            })
          }
        })
      //})
    },
    queryCampus() {
      // 查询校区（deptType = 1）
      treeselectByType("1").then(response => {
        this.campusOptions = response.data;
      })
    },
    selectQueryForm() {
      if(this.queryParamsClass.campusId === undefined || this.queryParamsClass.campusId === null) {
        this.$message({
            type: 'warning',
            message: '请选择校区'
          })
          return
      }
      //console.log(this.queryParams.campusId)
      listAllUserByDeptId(this.queryParamsClass.campusId).then(response => {
        this.masterUserOptions = []
        response.data.filter(data => {
          if(data.userName !== 'admin') {
            this.masterUserOptions.push(data)
          }
        })
      })
    },
     handleQueryClass() {
      this.queryParamsClass.pageNum = 1;
      this.getListClass();
    },
    /** 重置按钮操作 */
    resetQueryClass() {
      this.dateRange = [];
      this.resetForm("queryFormClass");
      this.handleQueryClass();
    },
    handleClassSelect() {
      // 循环列表
      this.openClassSelect = false
    },
    resetClassCancel() {
      this.openClassSelect = false
    },
    handleSelectionChangeClass(selection) {
      this.queryParams.classIds = selection.map(item => item.classId).toString()
      this.queryParams.classNames = selection.map(item => item.className).toString()
      //console.log(this.queryParams.classIds)
    },
    // ----------------------------- 以上是班级选择
  }
};
</script>
